<template>
  <div v-loading="loading">
    <el-form ref="ruleFormRef" :rules="rules" :model="publishForm">
      <el-form-item label="选择版本:" prop="publishVersion">
        <el-select v-model="publishForm.publishVersion" placeholder="选择版本" @change="versionChange">
          <el-option
            v-for="item in versionOptions"
            :key="item.versionId"
            :label="item.versionName"
            :value="item.versionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上线时间:" prop="publishType">
        <el-radio-group v-model="publishForm.publishType" @change="typeChange">
          <el-radio label="1">审核通过立即上线</el-radio>
          <el-radio label="2">定时上线</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="定时上线:" v-show="countdownTime" prop="publishTime">
        <el-date-picker
          v-model="publishForm.publishTime"
          type="datetime"
          placeholder="请选择上线时间"
        />
      </el-form-item>
      <el-form-item label="选择上线平台:" prop="publishPlate">
        <el-checkbox-group v-model="publishForm.publishPlate">
          <el-checkbox v-for="plate in platOptions" :key="plate.plat" :label="plate.plat" :disabled="!plate.isPublish">{{ plate.plat }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish(ruleFormRef)">发布</el-button>
        <el-button @click="closePublish">取消</el-button>
      </el-form-item>
      <el-alert title="没有可发布的版本" type="warning" v-show="infoVisible" />
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onBeforeMount, inject } from 'vue'
import type { VersionPublishQuery } from '../api/types'
import { VersionPublishApi, AppPublishApi } from '../api/'
import { useCounterStore } from '../stores/manage'
import type { FormRules, FormInstance } from 'element-plus'
import { ElNotification } from 'element-plus'

// 状态管理器
const manager = useCounterStore()

const ruleFormRef = ref<FormInstance>()
const loading = ref(false)

// 控制时间组件
const countdownTime = ref(false)

const infoVisible = ref(false)
const closePublish: Function = inject('closePublish') as Function

const typeChange = (val: string) => {
  if (val == '1') {
    countdownTime.value = false
  } else {
    countdownTime.value = true
  }
}

// 表单
const publishForm = reactive<VersionPublishQuery>({
  appId: '',
  publishVersion: '',
  publishType: '',
  publishTime: '',
  publishPlate: []
})

interface versionOption {
  versionId: string
  versionName: string
  plats: platOption[]
}

const checkPublishTime = (rule: any, value: any, callback: any) => {
  console.log(countdownTime.value)
  if (countdownTime.value) {
    if (value === '') {
      callback(new Error('请选择定时上线的时间'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const rules = reactive<FormRules<VersionPublishQuery>>({
  publishVersion: [{ required: true, message: '选择发布的版本', trigger: 'blur' }],
  publishType: [{ required: true, message: '选择发布的方式', trigger: 'blur' }],
  publishTime: [{ required: true, validator: checkPublishTime, trigger: 'blur' }],
  publishPlate: [
    { type: 'array', required: true, message: '请至少选择一个发布的平台', trigger: 'change' }
  ]
})

interface platOption {
  plat: string
  isPublish: boolean
}

const versionOptions = ref<versionOption[]>([])
const platOptions = ref<platOption[]>([])

onBeforeMount(() => {
  VersionPublishApi(manager.getAppId())
    .then((res) => {
      const data = res.data.data
      // 是否有可发布版本
      const isPublish = data.isPublish
      if (!isPublish) {
        infoVisible.value = true
        return
      }
      // 版本列表
      versionOptions.value = data.versions
    })
    .catch((error) => {
      console.log(error)
    })
})

const versionChange = (versionId: any) => {
  publishForm.publishPlate = []
  const versionData = versionOptions.value.find(version => version.versionId === versionId)
  if (versionData) {
    platOptions.value = versionData.plats
  }
}

// 发布
const onPublish = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      publishForm.appId = manager.getAppId()
      AppPublishApi(publishForm)
        .then((res) => {
          const result = res.data
          if (result.code != 200) {
            ElNotification({
              title: '失败',
              message: result.msg,
              type: 'error'
            })
          } else {
            closePublish()
            ElNotification({
              title: '成功',
              message: result.msg,
              type: 'success'
            })
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped>
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
</style>
